package com.heima.behavior.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: itheima
 * @create: 2022-07-29 11:26
 */
public class UserInterceptor implements HandlerInterceptor {


    /**
     * 拦截从网关路由来的请求，来的请求中包含自媒体用户信息，将自媒体用户信息存入ThreadLocal中
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login")) {
            return true;
        }
        //1.从请求头中获取用户信息
        String userID = request.getHeader("userId");
        String userName = request.getHeader("userName");
        //2.将信息存入ThreadLocal
        User user = new User();
        user.setUserId(Integer.parseInt(userID));
        user.setUserName(userName);
        UserThreadLocalUtil.set(user);
        return true;
    }

    /**
     * 清除ThreadLocal中数据
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocalUtil.remove();
    }
}
